package com.hnkywl.sts.action.jhgl;

import com.hnkywl.sts.entity.jhgl.Bgjhhz;
import com.hnkywl.sts.entity.jhgl.Bgjhhzmx;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.jhgl.BgjhhzService;
import com.hnkywl.sts.webservice.bg.client.WebServiceStub;
import com.hnkywl.sts.webservice.bg.request.SendPlanImportResult;
import com.hnkywl.sts.webservice.bg.util.StackTraceUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 向保供系统发送计划导入，通过webservice
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-6-5
 * Time: 上午9:56
 * To change this template use File | Settings | File Templates.
 */
@Component
public class SendPlanImport {
    private WebServiceStub webServiceStub;
    private WebserviceLogService webserviceLogService;
    private BgjhhzService bgjhhzService;

    /**
     * 发送计划导入到保供系统
     *
     * @param bgjhhzmxList
     * @return
     */
    public List<SendPlanImportResult> sendDataBg(List<Bgjhhzmx> bgjhhzmxList,String desc) {
        List<SendPlanImportResult> list = null;
        String resultCode = null;
        String exception = "";
        String xml = "";
        try {
            xml = getStringXml(bgjhhzmxList);
            if (StringUtils.isNotEmpty(xml)) {
                webServiceStub._getServiceClient().getOptions().setTimeOutInMilliSeconds(120000);//2分钟
//                WebServiceStub.Jhdr jhdr = new WebServiceStub.Jhdr();
//                jhdr.setStrXML(xml);
//                resultCode = webServiceStub.jhdr(jhdr).getJhdrResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
            exception = StackTraceUtil.getStackTrace(e);
        }
        webserviceLogService.saveClientLog(
                SendPlanImport.class.getName(),
                "sendDataBg",
                xml,
                resultCode,
                exception,
                desc
        );
        if(StringUtils.isNotEmpty(exception)) {
            return null;
        }
        if (null != resultCode) {
            return parseResultXML(resultCode);
        } else {
            return null;
        }
    }

    /**
     * 拼接成xml字符串
     *
     * @param bgjhhzmxList
     */
    private String getStringXml(List<Bgjhhzmx> bgjhhzmxList) {
        StringBuffer xmlSb = new StringBuffer();
        xmlSb.append("<?xml version='1.0' encoding='utf-8'?>");
        xmlSb.append("<request>");
        for (Bgjhhzmx mx : bgjhhzmxList) {
            if (null == mx || null == mx.getBgjhhz() || null == bgjhhzService.find(mx.getBgjhhz().getId()).getJhdw() || null == mx.getWzgg() || null == mx.getDhrq()) {
                return null;
            }
            Gsjg jhdw = bgjhhzService.find(mx.getBgjhhz().getId()).getJhdw();
            if (mx.getSbsl() == 0) continue;
            xmlSb.append("<plan>");
            xmlSb.append("<id>").append(mx.getBgjhhz().getId()).append("</id>");
            xmlSb.append("<planType>").append(getPlanType(mx.getBgjhhz())).append("</planType>");
            xmlSb.append("<plandepId>").append(jhdw.getId()).append("</plandepId>");
            xmlSb.append("<detailId>").append(mx.getId()).append("</detailId>");
            xmlSb.append("<description>").append(mx.getBgjhhz().getSm()).append("</description>");
            xmlSb.append("<code>").append(mx.getWzgg().getOldcode()).append("</code>");
            xmlSb.append("<sbsl>").append(mx.getSbsl()).append("</sbsl>");
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = sdf.format(mx.getDhrq());
            xmlSb.append("<deliveryDate>").append(strDate).append("</deliveryDate>");
            //牌号
            String ph = StringUtils.isEmpty(mx.getPh()) ? "" : "厂家品牌:【" + mx.getPh() + "】";
            //备注
            String bz = StringUtils.isEmpty(mx.getBz()) ? "" : "备注:【" + mx.getBz() + "】";
            xmlSb.append("<bz>").append(StringUtils.isEmpty(ph + bz) ? "NULL" : ph + bz).append("</bz>");
            xmlSb.append("</plan>");
        }
        xmlSb.append("</request>");
        return xmlSb.toString();
    }

    /**
     * 获取计划类型
     * ydjh:月度计划  jyljh急用料计划  zjjh:追加计划  bccbjh:补充储备计划
     *
     * @param bgjhhz
     * @return
     */
    private static String getPlanType(Bgjhhz bgjhhz) {
        if (null != bgjhhz.getType() && bgjhhz.getType().equals("ydjh")) {
            return "1";
        }
        if (null != bgjhhz.getType() && bgjhhz.getType().equals("jyljh")) {
            return "2";
        }
        if (null != bgjhhz.getType() && bgjhhz.getType().equals("zjjh")) {
            return "3";
        }
        if (null != bgjhhz.getType() && bgjhhz.getType().equals("bccbjh")) {
            return "5";
        }
        return "";
    }

    private List<SendPlanImportResult> parseResultXML(String xml) {
        List<SendPlanImportResult> list = new ArrayList<SendPlanImportResult>();
        SendPlanImportResult sendPlanImportResult;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = factory.newDocumentBuilder();
            String encoded = "utf-8";
            if (xml.indexOf("gb2312") != -1) {
                encoded = "gb2312";
            }
            Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes(encoded)));
            int nodeLength = doc.getElementsByTagName("plan").getLength();
            for (int i = 0; i < nodeLength; i++) {
                sendPlanImportResult = new SendPlanImportResult();
                String errorNumber = doc.getElementsByTagName("ErrorNumber").item(i).getFirstChild().getNodeValue();
                String errorReason = doc.getElementsByTagName("ErrorReason").item(i).getFirstChild().getNodeValue();
                String id = doc.getElementsByTagName("id").item(i).getFirstChild().getNodeValue();
                String detailId = doc.getElementsByTagName("detailId").item(i).getFirstChild().getNodeValue();
                sendPlanImportResult.setErrorNumber(errorNumber);
                sendPlanImportResult.setErrorReason(errorReason);
                sendPlanImportResult.setId(Long.valueOf(id));
                sendPlanImportResult.setDetailId(Long.valueOf(detailId));
                list.add(sendPlanImportResult);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }

    @Autowired
    public void setWebserviceLogService(WebserviceLogService webserviceLogService) {
        this.webserviceLogService = webserviceLogService;
    }

    @Autowired
    public void setWebServiceStub(WebServiceStub webServiceStub) {
        this.webServiceStub = webServiceStub;
    }
    @Autowired
    public void setBgjhhzService(BgjhhzService bgjhhzService) {
        this.bgjhhzService = bgjhhzService;
    }
}
